<?php
class MySQLConnectionPool {
	const DEFAULT_PORT = 3306;
	const TTL = 1800;
	const ERRMODE_SILENT = PDO::ERRMODE_SILENT;
	const ERRMODE_WARNING = PDO::ERRMODE_WARNING;
	const ERRMODE_EXCEPTION = PDO::ERRMODE_EXCEPTION;

	static private $connPool;

	static protected function _createNewConn($host, $port, $dbName, $dbUser, $dbPwd, $errMode = MySQLConnectionPool::ERRMODE_SILENT) {
		$conn = new PDO("mysql:host={$host};port={$port};dbname={$dbName}", $dbUser, $dbPwd);
		$conn->setAttribute(PDO::ATTR_ERRMODE, $errMode);
		$conn->exec("SET NAMES utf8");
		return $conn;
	}
	
	static public function getConnection($host, $port, $dbName, $dbUser, $dbPwd, $errMode = MySQLConnectionPool::ERRMODE_SILENT) {
		$key = "$host:$port:$dbName:$dbUser";
		if ( !isset(self::$connPool[$key]) || (!is_object(self::$connPool[$key]['connection'])) || self::$connPool[$key]['ttl'] < time() ) {
			self::$connPool[$key]['connection'] =  self::_createNewConn($host, $port, $dbName, $dbUser, $dbPwd, $errMode);
			self::$connPool[$key]['ttl'] = time() + self::TTL;
		}
		
		return self::$connPool[$key]['connection'];
	}
		
	static public function clearPool() {
		self::$connPool = null;
	}
}
?>
